<template>
    <div class="login">
        <div class="bg" :class="[{in: loginSuccess}, {blur: blur}]">
            <img draggable="false" :src="bg" alt="">
        </div>
        <div class="form">
            <div class="logo cursor" @click="getRandomBg"></div>
            <div class="title">{{this.title}}</div>
            <!-- <div class="code_left" @click="onClickCode" v-if="!isCode"></div> -->
            <div class="admin_left"  v-if="isCode" @click="isCode = false">
              <a >使用账号登录</a>
            </div>
            <div class="code_view" v-if="isCode">
              <img :src="imgUrl" alt="">
            </div>
            <Form ref="form" :model="form" :rules="rules" @submit.prevent="onSubmit" autocomplete="on" v-if="islogin && !isCode">
                <FormItem prop="username">
                    <Input type="text" name="username" autocomplete="on" v-model="form.username" placeholder="用户名">
                        <Icon type="ios-person-outline" slot="prepend"></Icon>
                    </Input>
                </FormItem>
                <FormItem prop="password">
                    <Input type="password" name="password" autocomplete="on" v-model="form.password" placeholder="密码">
                        <Icon type="ios-lock-outline" slot="prepend"></Icon>
                    </Input>
                </FormItem>
                <FormItem>
                  <div class="a" @click="onSetRegister">立即注册</div>
                </FormItem>
                <button class="btn-submit" type="submit" :disabled="disabled" @click.prevent="onSubmit">登录</button>
            </Form>
            <Form ref="register" :model="register" :rules="registerRules" autocomplete="on"  @submit.prevent="onRegister" v-show="!islogin">
                <FormItem prop="username">
                    <Input type="text" name="username" autocomplete="on" v-model="register.username" placeholder="用户名">
                        <Icon type="ios-person-outline" slot="prepend"></Icon>
                    </Input>
                </FormItem>
                <FormItem prop="phone">
                    <Input type="text" name="phone" autocomplete="on" v-model="register.phone" placeholder="手机号">
                        <Icon type="ios-person-outline" slot="prepend"></Icon>
                    </Input>
                </FormItem>
                <FormItem prop="password">
                    <Input type="password" name="password" autocomplete="on" v-model="register.password" placeholder="密码">
                        <Icon type="ios-lock-outline" slot="prepend"></Icon>
                    </Input>
                </FormItem>
                <FormItem prop="repassword">
                    <Input type="password" name="repassword" autocomplete="on" v-model="register.repassword" placeholder="确认密码">
                        <Icon type="ios-lock-outline" slot="prepend"></Icon>
                    </Input>
                </FormItem>
                <FormItem prop="very_code">
                    <Input type="text" name="very_code" autocomplete="on" v-model="register.very_code" placeholder="验证码">
                        <Icon type="ios-lock-outline" slot="prepend"></Icon>
                    </Input>
                  <SendMsg 
                    ref="sendmsg"
                    class="send-button"
                    :time="60"
                    ButtonName="发送短信"
                    :isDisabled="false"
                    @complete="OnSendNewCode">
                  </SendMsg>
                </FormItem>
                <FormItem>
                  <div class="a" @click="onSetLogin">已登录</div>
                </FormItem>
                <button class="btn-submit" type="submit" :disabled="disabled" @click.prevent="onRegister">注册</button>
            </Form>
            <Loader :status="status"></Loader>
        </div>
    </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getRandom, staticPath, download } from "@/util";
import SendMsg from '@/components/SendMsgItem'
const psValidator = (rules, value, callback) => {
  if (!(/^[1][3|4|5|6|7|8|9]\d{9}$/.test(value))) {
    callback(new Error("请输入正确的手机号"))
  } else {
    callback()
  }
}

export default {
  components: {
    SendMsg
  },
  data() {
    const conPsValidator = (rules, value, callback) => {
      if(this.register.password !== this.register.repassword) {
        callback(new Error("确认密码必须和密码一致"))
      } else {
        callback()
      }
    }
    return {
      imgUrl: '',
      title: '',
      codeImage: "/api/common/captcha",
      routeName: this.$route.query.name,
      routeOption: this.$router.options.routes,
      status: "pass",
      loginSuccess: !!window.loginSuccess,
      bg: "",
      blur: true,
      disabled: false,
      form: {
        username: "",
        password: "",
        code: "",
        remember: false
      },
      rules: {
        username: [
          { required: true, message: "请填写手机号", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请填写密码", trigger: "blur" },
          {
            type: "string",
            min: 4,
            message: "密码长度不能小于4位",
            trigger: "blur"
          }
        ],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
      islogin: true,
      isCode: false,
      register: {
        username: "",
        phone: "",
        password: "",
        repassword: "",
        very_code: ''
      },
      registerRules: {
        username: [
          { required: true, message: "请填写用户名", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "请填写手机号", trigger: "blur" },
          {
            required: true, validator: psValidator, trrigger: 'blur'
          }
        ],
        password: [
          { required: true, message: "请填写密码", trigger: "blur" },
          {
            type: "string",
            min: 4,
            message: "密码长度不能小于4位",
            trigger: "blur"
          }
        ],
        repassword: [
          { required: true, message: "请填写确认密码", trigger: "blur" },
          {
            type: "string",
            min: 4,
            message: "密码长度不能小于4位",
            trigger: "blur"
          },
          {
            required: true, validator: conPsValidator, trrigger: 'blur'
          }
        ]
      },
      socket: '',
      timeout: 2000,
      timeoutObj: null,
      serverTimeoutObj: null,
      lockReconnect: false,
      wsUrl: 'ws://139.196.141.25:9502',
      fiId: '',
      isMad: false
    };
  },
  mounted() {
    this.loginSuccess = false;
    window.isMad  = false
    this.getRandomBg();
    // this.getCode()
      // this.init()
    this.$store.dispatch('getInfo').then(data => {
      this.title = data.userName
    })
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.routeName = from.name
    })
  },
  computed: {
    ...mapGetters(['user'])
  },
  methods: {
    createWebSocket() {
        try{
            if('WebSocket' in window){
                this.socket = new WebSocket(this.wsUrl);
            }
            // initEventHandle();
            // this.init()
        }catch(e){
            this.reconnect(url);
            console.log(e);
        }
    },
    //心跳检测
    heartCheck() {
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        var self = this;
        this.timeoutObj = setTimeout(function(){
          // console.log("dnqoi1")
            //这里发送一个心跳，后端收到后，返回一个心跳消息，
            //onmessage拿到返回的心跳就说明连接正常
            self.socket.send("wechat_login");
            console.log("wechat_login!")
            self.serverTimeoutObj = setTimeout(function(){//如果超过一定时间还没重置，说明后端主动断开了
                console.log("我很无语")
                self.socket.close();     //如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
            }, self.timeout)
        }, self.timeout)
    },
    reconnect(url) {
        let self = this
        if(this.lockReconnect) return;
        this.lockReconnect = true;
        setTimeout(function () {     //没连接上会一直重连，设置延迟避免请求过多
            console.log("进来没")
            // self.createWebSocket(this.wsUrl);
            self.init()
            self.lockReconnect = false;
        }, 2000);
    },
    init() {
      this.createWebSocket()
      this.socket.onopen =  () => {
        this.heartCheck();      //心跳检测重置
        console.log("llws连接成功1!"+new Date().toLocaleString());
      };
      this.socket.onmessage = (data) => {
        let res = ''
          if (!window.isMad) this.heartCheck(); 
          if (data.data.indexOf('{') > -1) {
            res = JSON.parse(data.data)
          }
          if (res.type == "storage") this.fiId = res.fdId
          if (res.type == 'login') {
            // setTimeout(() => {
              window.isMad = true
              this.onCancel()
              this.$store.dispatch('userLogin', {'name': '', 'token': res.token_arr.access_token}, true)
              this.$router.replace("/home/platform/list");
              return
            // }, 200)
          }
        console.log(this.isMad)
        // this.updated(data)
      };
      this.socket.onclose =  () => {
        // this.reconnect();
        console.log("llws连接关闭!"+new Date().toLocaleString());
      };
      this.socket.onerror =  () => {
        // debugger
        // this.reconnect();
        console.log("llws连接错误!");
      };
    },
    onCancel() {
      this.socket.close()
    },
    onClickCode() {
      this.$ajaxGet('/login/getWechatCode?'+ `fid=${this.fiId}`).then(res => {
        this.isCode = true
        this.imgUrl = res
      })
    },
    isJSON(str) {
        if (typeof str == 'string') {
            try {
                var obj=JSON.parse(str);
                if(typeof obj == 'object' && obj ){
                    return true;
                }else{
                    return false;
                }

            } catch(e) {
                console.log('error：'+str+'!!!'+e);
                return false;
            }
        }
        console.log('It is not a string!')
    },
    OnSendNewCode() {
      this.$ajaxGet('/login/getVerufyCode', { phone: this.register.phone }).then(res => {
        this.$refs.sendmsg.sendMsg("OldPhoneButtonName", "isOldPhoneDisabled", "time")
        this.$Notice.success({
          title: "返回验证码成功"
        });
      })
    },
    getRandomBg() {
      let month = new Date().getMonth() + 1;
      let season = "spring";
      switch (month) {
        case 2:
        case 3:
        case 4:
        case 5:
          season = "spring";
          break;
        case 6:
        case 7:
        case 8:
          season = "summer";
          break;
        case 9:
        case 10:
        case 11:
          season = "autumn";
          break;
        case 12:
        case 1:
          season = "winter";
          break;
      }
      let bg = `${staticPath}/season/${season}/${getRandom(1, 30)}.jpg`;
      let img = new Image();
      img.src = bg;
      this.blur = true;
      this.bg = bg + "!64w";
      img.onload = () => {
        // 故意延迟 500ms ,让不懂的人觉得酷炫
        setTimeout(() => {
          this.bg = bg;
          this.blur = false;
        }, 500);
      };
    },
    onSubmit() {
      if (this.status === "loading" || this.disabled) return;
      this.$refs.form.validate(valid => {
        if (valid) {
          let param = {
            'username': this.form.username,
            'password': this.form.password
          }
          this.status = 'loading'
          this.disabled = true
          this.$ajaxPost('/login/login', param).then(data => {
            // this.onCancel()
            this.$store.dispatch('userLogin', {'name': this.form.username, 'token': data.access_token}, true)
            this.status = 'pass'
            this.disabled = false
            setTimeout(() => {
              this.login()
            }, 200)
          }).catch(() => {
            this.status = 'pass'
            this.disabled = false
          })
        }
      });
    },
    login() {
      this.$Notice.success({
        title: "登录成功"
      });
      if (this.routeName) {
        let query = this.$route.query;
        if (this.routeName === "refuse") {
          this.routeName = "home/platform/list";
        }
        let routers = this.$router.options.routes
        const hasPower = (e) => {
          e.forEach(todo => {
            if (todo.name == this.routeName) {
              this.routeName = todo.name
            }
            if (todo.children && todo.children.length) {
              hasPower(todo.children)
            }
          })
        }
        hasPower(routers)
        query.name = null;
        // delete query.name;
        this.$router.replace({
          name: "home/platform/list",
          query: query
        });
      } else {
        this.$router.replace("/home/platform/list");
      }
    },
    onSetRegister() {
      this.islogin = false
      this.$nextTick(() => {
        this.$refs.register.resetFields()
      })
    },
    onSetLogin() {
      this.islogin = true
    },
    onRegister() {
      let url = '/login/register'
      let param = this.register
      this.$jsonPost(url,param).then(res => {
        this.$Notice.success({
          title: "注册成功"
        });
        this.islogin = true
      })
    }
  },
  watch: {
    routeOption() {
    }
  }
};
</script>


